


cc.Class({
    extends: cc.Component,

    properties: {
        piecePrefab: cc.Prefab,                  // 棋子预制
        touchDotPrefab: cc.Prefab                // 触摸点预制
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        cc.debug.setDisplayStats(false);

        const hLines = 15;                       // 水平线数量
        const vLines = 15;                       // 垂直线数量
        this.blockWidth = (this.node.width / (vLines-1)).toFixed(2);     // 每块区域的宽度
        this.blockHeight = (this.node.height / (hLines-1)).toFixed(2);   // 每块区域的高度

        this.boardPosArray = [];                 // 棋盘上所有点的坐标
        this.getBoardPos(hLines, vLines);       

        this.currentPlayer = 'BLACK';            // 当前着步方

        this.initTouchDots();                    // 添加所有触摸点
    },

    getBoardPos(hLines, vLines) {          
        for (let i=0; i<hLines; i++) {
            for (let j=0; j<vLines; j++) {
                let x = j*this.blockWidth;
                let y = i*this.blockHeight;
                this.boardPosArray.push([x, y, '0']);
            }
        }
    },

    initTouchDots() {
        for (let i=0; i<this.boardPosArray.length; i++) {
            let touchDot = cc.instantiate(this.touchDotPrefab);
            touchDot.opacity = 0;
            this.node.addChild(touchDot);
            touchDot.getComponent('TouchDot').initBoard(this);
            touchDot.setPosition(this.boardPosArray[i][0], this.boardPosArray[i][1])
        }
    },

    putPiece(x, y) {
        // 放置棋子，并更新着步方xx
        let is_ok = this.check(x.toFixed(2), y.toFixed(2));               
        if (!is_ok)
            return;

        let piece = cc.instantiate(this.piecePrefab);
        this.node.addChild(piece);
        piece.getComponent('Piece').setPic(this.currentPlayer);
        piece.width = this.blockWidth*0.9;
        piece.height = this.blockHeight*0.9;
        piece.setPosition(x, y)

        if (this.currentPlayer == 'BLACK') {
            this.currentPlayer = 'WHITE';
        }
        else {
            this.currentPlayer = 'BLACK';
        }
    },

    check(x, y) {
        // 查看当前位置是否可以着步
        for (let i=0; i<this.boardPosArray.length; i++) {
            if (x==this.boardPosArray[i][0] && y==this.boardPosArray[i][1]){
                if (this.boardPosArray[i][2]=='0') {
                    // 可以放置，并更新数组
                    this.boardPosArray[i][2] = '1';
                    return true;
                }
                else {
                    // 已有棋子，不可放置
                    return false;
                }
            }
        }
    }
});
